using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using YooAsset;
using YooAsset.Editor;

public class YooAssetPackTool
{
    [MenuItem("YooAsset1/Build YooAsset Pack")]
    public static void BuildYooAssetPack()
    {
        string packageName = "MainPackage";
        CollectAssets(packageName);
        BuildYooAssetPack(packageName);
    }

    public static void CollectAssets(string packageName)
    {
        // key:GroupName,value:(AssetPath,GroupName,GroupDesc)
        Dictionary<string, (string, string, string)> assets = new Dictionary<string, (string, string, string)>()
        {
            { "Prefabs", ("/Prefabs", "Prefabs", "prefabs") },
            { "Materials", ("/Materials", "Materials", "materials") },
            { "Scenes", ("/Scenes", "Scenes", "scenes") },
        };
        var curPackList = AssetBundleCollectorSettingData.Setting.Packages;
        var package = curPackList.Find(x => x.PackageName == packageName);
        if (package == null)
        {
            package = new AssetBundleCollectorPackage();
            package.PackageName = packageName;
            package.PackageDesc = packageName;
            package.Groups = new List<AssetBundleCollectorGroup>();
            package.EnableAddressable = true;
            curPackList.Add(package);
            Debug.Log($"{packageName} not exist, create it");
        }

        foreach (var pair in assets)
        {
            string assetPath = pair.Value.Item1;
            string groupName = pair.Value.Item2;
            string groupDesc = pair.Value.Item3;
            var group = GetAndCreateGroup(package.Groups, groupName, groupDesc);
            AddAsset(group, Application.dataPath + assetPath);
        }

        AssetBundleCollectorSettingData.SaveFile();
    }

    static AssetBundleCollectorGroup GetAndCreateGroup(List<AssetBundleCollectorGroup> groups, string groupName,
        string groupDesc)
    {
        var group = groups.Find(x => x.GroupName == groupName);
        if (group == null)
        {
            group = new AssetBundleCollectorGroup()
            {
                GroupName = groupName,
                GroupDesc = groupDesc,
                Collectors = new List<AssetBundleCollector>()
            };
            groups.Add(group);
            Debug.Log($"{groupName} not exist, create it");
        }

        return group;
    }

    static void AddAsset(AssetBundleCollectorGroup group, string assetPath)
    {
        DirectoryInfo dir = new DirectoryInfo(assetPath);
        foreach (FileInfo file in dir.GetFiles())
        {
            string filePath = file.FullName;
            if (filePath.ToLower().EndsWith(".prefab")
                || filePath.ToLower().EndsWith(".unity")
                || filePath.ToLower().EndsWith(".mat")
                || filePath.ToLower().EndsWith(".shader")
                || filePath.ToLower().EndsWith(".png")
                || filePath.ToLower().EndsWith(".jpg"))
            {
                string objPath = filePath.Replace(Application.dataPath, "Assets");
                // var obj = AssetDatabase.LoadAssetAtPath(objPath, typeof(Object));
                // if (obj != null)
                {
                    Debug.Log($"{objPath} check");
                    var curColl = group.Collectors.Find(x => x.CollectPath == objPath);
                    if (curColl == null)
                    {
                        Debug.Log($"{objPath} not int group ,Add it");
                        curColl = new AssetBundleCollector()
                        {
                            CollectPath = objPath,
                            CollectorType = ECollectorType.MainAssetCollector,
                            CollectorGUID = AssetDatabase.AssetPathToGUID(objPath),
                        };
                        group.Collectors.Add(curColl);
                    }
                }
            }
        }
        // foreach (var obj in objs)
        // {
        //    string objPath = AssetDatabase.GetAssetPath(obj);
        //    Debug.Log($"AddAsset {objPath} ");
        //    var curColl = group.Collectors.Find(x => x.CollectPath == objPath);
        //    if (curColl == null)
        //    {
        //       Debug.Log($"{objPath} not int group ,Add it");
        //       curColl = new AssetBundleCollector()
        //       {
        //          CollectPath = objPath,
        //          CollectorType = ECollectorType.MainAssetCollector,
        //       };
        //       group.Collectors.Add(curColl);
        //    }
        // }
    }

    public static void BuildYooAssetPack(string packageName)
    {
        BuildTarget buildTarget = BuildTarget.StandaloneOSX;
        string packageVersion = "1.0";
        bool isIcrementBuild = true;

        Debug.Log($"开始构建 : {buildTarget}");

        var buildoutputRoot = AssetBundleBuilderHelper.GetDefaultBuildOutputRoot();
        var streamingAssetsRoot = AssetBundleBuilderHelper.GetStreamingAssetsRoot();

        // 构建参数
        ScriptableBuildParameters buildParameters = new ScriptableBuildParameters();
        buildParameters.BuildOutputRoot = buildoutputRoot;
        buildParameters.BuildinFileRoot = streamingAssetsRoot;
        buildParameters.BuildPipeline = EBuildPipeline.ScriptableBuildPipeline.ToString();
        buildParameters.BuildBundleType = (int)EBuildBundleType.AssetBundle; //必须指定资源包类型
        buildParameters.BuildTarget = buildTarget;
        buildParameters.PackageName = packageName;
        buildParameters.PackageVersion = packageVersion;
        buildParameters.VerifyBuildingResult = true;
        buildParameters.EnableSharePackRule = true; //启用共享资源构建模式，兼容1.5x版本
        buildParameters.FileNameStyle = EFileNameStyle.HashName;
        buildParameters.BuildinFileCopyOption = EBuildinFileCopyOption.None;
        buildParameters.BuildinFileCopyParams = string.Empty;
        // buildParameters.EncryptionServices = CreateEncryptionInstance(); // 不加密
        buildParameters.CompressOption = ECompressOption.LZ4;
        buildParameters.ClearBuildCacheFiles = !isIcrementBuild; //不清理构建缓存，启用增量构建，可以提高打包速度！
        buildParameters.UseAssetDependencyDB = true; //使用资源依赖关系数据库，可以提高打包速度！

        // 执行构建
        ScriptableBuildPipeline pipeline = new ScriptableBuildPipeline();
        var buildResult = pipeline.Run(buildParameters, true);
        if (buildResult.Success)
        {
            Debug.Log($"构建成功 : {buildResult.OutputPackageDirectory}");
        }
        else
        {
            Debug.LogError($"构建失败 : {buildResult.ErrorInfo}");
        }
    }


// 从构建命令里获取参数示例
    private static string GetBuildPackageName()
    {
        foreach (string arg in System.Environment.GetCommandLineArgs())
        {
            if (arg.StartsWith("buildPackage"))
                return arg.Split("="[0])[1];
        }

        return string.Empty;
    }
}